$(window).on('load resize', function() {
	var titleHt = $('.sys-title:eq(0)').outerHeight();
	var ht = $(window).height() - titleHt - 10;
	$('#nav').height(ht);
});

// 获取导航 json 配置文件
$.getJSON('include/js/nav.json?' + (+new Date()), function(navArr) {
	buildNav(navArr);

	var pageURL = navArr[0].url || navArr[0].subNav[0].url;
	$('#mainCont').attr('src', pageURL);
});

/**
 * 构建导航
 * @param {array} navArr - 导航菜单数组
 */
function buildNav(navArr) {
	var html = '';
	for (var i = 0; i < navArr.length; i++) {
		var active = i === 0 ? ' is-active' : '',
			hasSubNav = (navArr[i].subNav && navArr[i].subNav.length) ? 'has-subnav' : '';
		html += '<li class="nav-item' + active + ' ' + hasSubNav + '">' +
					'<a class="nav-item-link" ' +
						'href="' + (navArr[i].url || 'javascript:;') + '" target="mainCont">';

		if (navArr[i].icon) {
			html +=		'<i class="iconfont icon-' + navArr[i].icon + '"></i>';  // 图标
		}

		html +=			navArr[i].name +
					'</a>';

		var subNav = navArr[i].subNav;
		if (subNav && subNav.length) {
			html += '<ul class="subnav">';
			for (var j = 0; j < subNav.length; j++) {
				html += '<li>' +
							'<a href="' + navArr[i].base + subNav[j].url + '" target="mainCont">' +
								subNav[j].name +
							'</a>' +
						'</li>';
			}
			html += '</ul>';
		}
		subNav = null;
		html +=	'</li>';
	}
	$('#nav').html(html);
	html = null;

	// 导航折叠展开
	$('.sys-title').click(function() {
		$(this).parent().toggleClass('is-fold');
	});

	// 导航链接点击
	bindNavEvt($('#nav'));
}

/**
 * 绑定导航点击事件
 * @param {object} nav - 导航 jQ 对象
 */
function bindNavEvt(nav) {
	var lastSubNav = null;
	nav.on('click', 'a', function(e) {
		var self = $(this),
			parent = self.parents('.nav-item'),
			subNav = parent.children('ul');

		if (self.parent().is('.nav-item')) {  // 一级栏目
			if (lastSubNav) {
				lastSubNav.hide(240);
			}

			if (subNav.length) {
				if (!subNav.is(':animated')) {
					subNav.slideToggle(240);
					lastSubNav = subNav;
				}
			}
		} else {  // 二级栏目
			if (nav.parent().hasClass('is-fold')) {  // 折叠状态
				subNav.hide();  // 点击后自动隐藏二级菜单
			}
		}

		e.stopPropagation();
	});
}
